﻿using Infrastructure.Config.Core.External;
using Microsoft.ApplicationInsights.AspNetCore;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DependencyCollector;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;
using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Shared.Service.Logging.ApplicationInsights
{
    public static class ApplicationInsightsExtension
    {
        public static void AddTelemetry(this IServiceCollection services, IConfiguration configuration)
        {
            var options = new ApplicationInsightsApiOptions();
            configuration.GetSection("ApplicationInsights").Bind(options);
            if (options.IsEnable)
            {
                services.ConfigureTelemetryModule<QuickPulseTelemetryModule>((module, o) =>
                    module.QuickPulseServiceEndpoint = options.QuickPulse.EndpointAddress
                );

                services.AddSingleton<IApplicationIdProvider, ApplicationInsightsApplicationIdProvider>(_ =>
                    new ApplicationInsightsApplicationIdProvider()
                    {
                        ProfileQueryEndpoint = options.ProfileQuery.EndpointAddress
                    });

                services.AddSingleton<ITelemetryChannel>(_ => new ServerTelemetryChannel()
                {
                    EndpointAddress = options.TelemetryChannel.EndpointAddress
                });

                services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) =>
                {
                    module.EnableSqlCommandTextInstrumentation = true;
                });

                services.AddSingleton<ITelemetryProcessorFactory>(
                    new SimpleTelemetryProcessorFactory(
                        next => new IgnoreRequestsTelemetryProcessor(next)));

                services.AddSingleton<ITelemetryInitializer, CustomTelemetryInitializer>();
                services.AddApplicationInsightsTelemetry(options.InstrumentationKey);
            }
        }
    }
}

